package com.spider.im.chat.message.massage;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.protobuf.Parser;
import com.spider.im.chat.entity.ChatGroupUser;
import com.spider.im.chat.annotation.MessageTypeHandler;
import com.spider.im.chat.proto.ChatProto;
import com.spider.im.chat.service.ChatGroupUserService;
import com.spider.im.chat.message.AbstractMessageStrategy;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
@MessageTypeHandler(type = ChatProto.MessageType.GROUP_CHAT)
public class GroupChatStrategy extends AbstractMessageStrategy<ChatProto.GroupChatRequest> {

    @Resource
    private ChatGroupUserService chatGroupUserService;

    @Override
    public Parser<ChatProto.GroupChatRequest> getParser() {
        return ChatProto.GroupChatRequest.parser();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, ChatProto.GroupChatRequest message) {

        log.info("发送群聊消息: {}", message.getMessage());
        long groupId = message.getGroupId();

        //获取群聊的在线用户
        List<ChatGroupUser> chatGroupUserList = chatGroupUserService.list(new LambdaQueryWrapper<ChatGroupUser>().eq(ChatGroupUser::getGroupId, groupId));
        if (CollectionUtil.isEmpty(chatGroupUserList)) {
            log.warn("组TargetGroupId {} 没有人. Message not sent.", groupId);
            return;
        }
        //拼装消息
        ChatProto.MessageWrapper wrapper = getMessageWrapper(true, message.getMessage());
        //遍历群聊的在线用户,发送消息
        chatGroupUserList.forEach(chatGroupUser -> {
            Channel targetChannel = activeChannels.get(chatGroupUser.getUserId());
            if (targetChannel != null && targetChannel.isActive()) {
                log.info("给用户发送消息 {},message:{}.", chatGroupUser.getUserId(),message.getMessage());
                targetChannel.writeAndFlush(wrapper);
                this.sendResponse(targetChannel, wrapper);
            } else {
                log.warn("用户 {} 不在线. Message not sent.", chatGroupUser.getUserId());
            }
        });
        boolean success = true;
        String messageR = "消息发送成功";

        ChatProto.MessageWrapper wrapperResp = getMessageWrapper(success,messageR);
        this.sendResponse(ctx.channel(), wrapperResp);
    }

    /**
     * 构建消息包装
     *
     * @return
     */
    private static ChatProto.MessageWrapper getMessageWrapper(boolean success, String message) {
        ChatProto.Response response = ChatProto.Response.newBuilder()
                .setSuccess(success)
                .setMessage(message)
                .build();
        return ChatProto.MessageWrapper.newBuilder()
                .setType(ChatProto.MessageType.GROUP_CHAT)
                .setPayload(response.toByteString())
                .build();
    }
}
